package com.cse.engine;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import com.cse.engine.subEngine.Engine;

/**
 * 单例模式</br>
 * 引擎工厂类</br>
 * 存放引擎信息</br>
 * 使用动态代理创建引擎类的代理</br>
 * @author Mutear
 *
 */
public class EngineFactory {
	
	/**
	 * 引擎信息
	 */
	private Map<String, EngineInfo> engines;
	/**
	 * 该类的单例
	 */
	private static EngineFactory engineFactory = null;
	
	private EngineFactory(){
		engines = new HashMap<String, EngineInfo>();
		// 从配置文件中获取引擎信息
		Properties properties = new Properties();
		InputStream inputStream = getClass().getResourceAsStream("/engines.properties");
		try {
			properties.load(inputStream);
			Enumeration enumeration = properties.propertyNames();
			while(enumeration.hasMoreElements()){
				String key = (String) enumeration.nextElement();
				String property = properties.getProperty(key);
				EngineInfo engineInfo = new EngineInfo(key, property);
				engines.put(key, engineInfo);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static EngineFactory getEngineFactory(){
		if(null == engineFactory){
			engineFactory = new EngineFactory();
		}
		return engineFactory;
	}
	
	/**
	 * 生产引擎代理对象
	 * @param engineName
	 * @return
	 */
	public Engine createEngine(String engineName){
		EngineProxy engineProxy = new EngineProxy();
		engineProxy.bind(engineName);
		return engineProxy;
	}

	/**
	 * 返回引擎信息列表
	 * @return
	 */
	public List<EngineInfo> getEngineList() {
		List<EngineInfo> result = new ArrayList<EngineInfo>();
		Set<Entry<String, EngineInfo>> items = engines.entrySet();
		for(Iterator<Entry<String, EngineInfo>> it = items.iterator(); it.hasNext();){
			Entry<String, EngineInfo> entry = it.next();
			result.add(entry.getValue());
		}
		return result;
	}
	
	public String getEngineClassName(String engineName){
		return engines.get(engineName).getClassName();
	}
	
}
